package org.sxf.app.sign.provider;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.util.LogUtils;

import org.sxf.app.sign.constants.Constants;
import org.sxf.app.sign.data.DataCacheSingleton;
import org.sxf.app.sign.model.MsgRepBean;
import org.sxf.app.sign.model.MsgReqBean;
import org.sxf.app.sign.utils.CosUtils;
import org.sxf.app.sign.utils.MD5Utils;
import org.sxf.app.sign.utils.PBOCDES;
import org.sxf.app.sign.utils.Utility;

import java.util.HashMap;

/**
 * Created by zqc on 17/1/16.
 */
public class MsgHandler {

    public final static int NEED_TOKEN = 0xF0;
    public final static int NO_NEED_TOKEN = 0xF1;

    public static String msgEncode(String apiVersion, HashMap reqMap, int isNeedT){
        return msgEncode(apiVersion, JSON.toJSONString(reqMap), isNeedT);
    }

    public static String msgEncode(String apiVersion, String reqData, int isNeedT){
        String result = "";
        try {
            MsgReqBean reqBean = new MsgReqBean();
            reqBean.v = apiVersion;
            if (isNeedT == NEED_TOKEN){
                reqBean.t = DataCacheSingleton.getInstance().getTk();
            }else if (isNeedT == NO_NEED_TOKEN){
                reqBean.t = "";
            }
            reqBean.rd = reqData;
//            reqBean.s = CosUtils.cosSub(MD5Utils.MD5(reqData), 1,4);
            reqBean.s = MD5Utils.MD5(reqData);
            result = JSON.toJSONString(reqBean);

            result = PBOCDES.hex(PBOCDES.pboc3DESEncryptForLong(Constants.SES_KEY, result.getBytes(), true, true));

        }catch (Exception e){
            LogUtils.e(Utility.getStackTrace(e));
        }
        return result.toUpperCase();
    }


    public static String msgDecrypt(String msg){
        byte[] deCode = PBOCDES.pboc3DESDecrypt(Constants.SES_KEY, PBOCDES.parseBytes(msg));
        byte[] len = new byte[]{deCode[0], deCode[1]};
        LogUtils.d(Utility.bytesToHexString(len));
        int length = Integer.parseInt(Utility.bytesToHexString(len),16);
        byte[] value = new byte[length];
        System.arraycopy(deCode,2,value,0,length);
        String result = new String(value);
        LogUtils.d("decrypt:" + result);
        return result;
    }

    public static boolean checkSignature(MsgRepBean repBean){
        try {
            if (repBean.s.equalsIgnoreCase(MD5Utils.MD5(repBean.rd))){
                return true;
            }
        }catch (Exception e){
            LogUtils.e(Utility.getStackTrace(e));
        }
        return false;
    }

}
